package com.twotwoshop.service.search.interceptor;


import cn.hutool.core.bean.BeanUtil;
import com.twotwoshop.domin.user.dtos.UserDto;
import com.twotwoshop.domin.user.pojos.ApUser;
import com.twotwoshop.util.thread.AppThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.twotwoshop.commom.redis.RedisConstants.LOGIN_USER_KEY;
import static com.twotwoshop.commom.redis.RedisConstants.LOGIN_USER_TTL;

/**
 * 自媒体端拦截器
 */
@Slf4j
@RequiredArgsConstructor
public class AppTokenInterceptor implements HandlerInterceptor {


    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 前置处理 得到header中的用户信息 并且存入到当前线程中
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //3.获取token - 支持多种方式获取
        String token = null;

        // 从Header中获取Authorization
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isNotBlank(authorization) && authorization.startsWith("Bearer ")) {
            token = authorization.substring(7);
        }

        //判断token是否存在
        if (StringUtils.isBlank(token)) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }


        //5.判断token是否有效
        //2.基于token 从 Redis获取用户信息
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(LOGIN_USER_KEY + token);

        //3.判断用户是否存在
        if (userMap.isEmpty()) {
            log.warn("用户不存在");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }

        //4.将查询到的Hash数据转化为UserDTO对象                 不忽略转换过程的错误
        UserDto userDto = BeanUtil.fillBeanWithMap(userMap, new UserDto(),false);
        ApUser apUser = BeanUtil.copyProperties(userDto, ApUser.class);


        AppThreadLocalUtil.setUser(apUser);


        //6.刷新tocken有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY+token,LOGIN_USER_TTL, TimeUnit.MINUTES);


        return true;
    }


    /**
     * 清理线程中的数据
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("清理threadlocal...");
        AppThreadLocalUtil.removeUser();
    }

    /**
     * 清理线程中的数据
     * @param request
     * @param response
     * @param handler
     * @param
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("清理threadlocal...");
        AppThreadLocalUtil.removeUser();
    }
}
